//
//  CYAssetManagerVC.m
//  CreditAddressBook
//
//  Created by LE on 16/1/8.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "CYAssetManagerVC.h"
#import "CYButtonView.h"
#import "CYLoginHttpTool.h"
#import "CYJumpsTool.h"
#import "DSNavigationBar.h"
#import "UIInfomationView.h"
#import "LEMDLib.h"
#import "CYDiscoveryHttpTool.h"
#import "CYUserAccount.h"
#import "MBProgressHUD+MJ.h"
#import "CYQueryandPayVC.h"
#import "CYGFBTool.h"
#import "LEDIYHeader.h"
#import "LEAlertView+LE.h"
#import "CYRentTransfer.h"
#import "MDSlider.h"
#import "CYCarUserAccount.h"
#import "CYGetdealCodeVC.h"
#import "CYJsonInfo.h"
#import "NSObject+MJKeyValue.h"
#import "CYBankcardBandTableViewController.h"
#import "UIAlertView+Block.h"
#import "CYAssetDetailVC.h"

@interface CYAssetManagerVC ()<UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate>

@property(nonatomic, weak) UITableView *tableview;
@property(nonatomic, weak) UILabel *balanceL;
@property(nonatomic, weak) UILabel *tip;
@property(nonatomic, strong) NSString *type;
@property(nonatomic, strong) UITextField *dealcode;
@property(nonatomic, strong) UITextField *moneycount;
@property(nonatomic, strong) NSString *bandcheck;

@property(nonatomic, assign) BOOL isRefresh;
@end

@implementation CYAssetManagerVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self loadBalance];
    [self setupNavigationView];
    [self setupTipView];
}

- (void)setupTable {
    UITableView *table = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    [self.view addSubview:table];
    table.dataSource = self;
    table.delegate = self;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableview = table;
    //tableview头部view
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 150)];
    headerView.backgroundColor = CYNaviThemeColor;
    table.tableHeaderView = headerView;
    UILabel *balanceL = [[UILabel alloc] init];
    self.balanceL = balanceL;
    balanceL.text = @"0";
    balanceL.textColor = [UIColor whiteColor];
    balanceL.font = [UIFont boldSystemFontOfSize:50];
    [headerView addSubview:balanceL];
    [balanceL autoAlignAxisToSuperviewAxis:ALAxisVertical];
    [balanceL autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:8];
    UILabel *label = [[UILabel alloc] init];
    label.text = @"余额(元)";
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:20];
    [headerView addSubview:label];
    [label autoAlignAxisToSuperviewAxis:ALAxisVertical];
    [label autoPinEdge:ALEdgeBottom toEdge:ALEdgeTop ofView:balanceL];
}
/**
 *  加载余额
 */
- (void)loadBalance {
    CYUser *user = [CYLoginHttpTool userData].user;
    if (user) {
        [MBProgressHUD showMessage:nil toView:self.view];
        [CYDiscoveryHttpTool getUserAccountBalanceWithParam:@{@"userId": user.userId, @"token": user.token} success:^(CYUserAccount *userAccount) {
            [MBProgressHUD hideHUDForView:self.view];
            [self setupTable];
            [self setupRefresh];
            //[self loadCarUserAccount];
            self.balanceL.text = [NSString stringWithFormat:@"%@", userAccount.balance];
        } failure:^(NSString *message, BOOL isLogin) {
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:message];
            if (!isLogin) {
                [self.navigationController popViewControllerAnimated:NO];
                [CYLoginHttpTool logoutWithController:self];
            } else {
                self.tip.hidden = NO;
            }
            self.balanceL.text = @"--";
        }];
    } else {
        self.balanceL.text = @"--";
    }
}

- (void)setupRefresh {
    CYWeakObject(wself, self);
    LEDIYHeader *header = [LEDIYHeader headerWithRefreshingBlock:^{
        [wself refreshBalance];
    }];
    self.tableview.mj_header = header;
}

- (void)refreshBalance {
    CYUser *user = [CYLoginHttpTool userData].user;
    if (user) {
        [CYDiscoveryHttpTool getUserAccountBalanceWithParam:@{@"userId": user.userId, @"token": user.token} success:^(CYUserAccount *userAccount) {
            [MBProgressHUD hideHUDForView:self.view];
            self.balanceL.text = [NSString stringWithFormat:@"%@", userAccount.balance];
            [self.tableview.mj_header endRefreshing];
        } failure:^(NSString *message, BOOL isLogin) {
            [self.tableview.mj_header endRefreshing];
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:message];
            if (!isLogin) {
                [self.navigationController popViewControllerAnimated:NO];
                [CYLoginHttpTool logoutWithController:self];
            }
            self.balanceL.text = @"--";
        }];
    } else {
        self.balanceL.text = @"--";
    }
}

- (void)setupTipView {
    UILabel *tip = [[UILabel alloc] init];
    tip.text = @"网络错误，请稍后再试";
    tip.font = [UIFont boldSystemFontOfSize:20];
    tip.textColor = [UIColor grayColor];
    [self.view addSubview:tip];
    [tip autoCenterInSuperview];
    self.tip = tip;
    tip.hidden = YES;
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CYUser *user = [CYLoginHttpTool userData].user;
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    if (indexPath.section == 0) {
        UIImage *icon = [UIImage imageWithName:@"1"];
        CGSize itemSize = CGSizeMake(30, 30);
        UIGraphicsBeginImageContextWithOptions(itemSize, NO ,0.0);
        CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
        [icon drawInRect:imageRect];
        
        cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        cell.textLabel.text = @"我的银行卡";
        cell.detailTextLabel.textColor = [UIColor lightGrayColor];
        [CYHttpTool postWithURL:[CYURL shared].getBandCardStatus params:@{@"userId":user.userId,@"token":user.token} success:^(id json) {
                CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
            if (jsoninfo.isSuccess) {
                NSDictionary *data = jsoninfo.data;
                NSString *str = [data valueForKey:@"cardNo"];
                _bandcheck = str;
                cell.detailTextLabel.text = str;
            }

            } failure:^(NSError *error) {

            }];
       // cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else if (indexPath.section == 3) {
        CYButtonView *tabBarView = [[CYButtonView alloc] init];
        [cell addSubview:tabBarView];
        [tabBarView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
        [self addTabBar:tabBarView];
    } else if (indexPath.section == 2) {
        UIImage *icon = [UIImage imageWithName:@"4"];
        CGSize itemSize = CGSizeMake(30, 30);
        UIGraphicsBeginImageContextWithOptions(itemSize, NO ,0.0);
        CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
        [icon drawInRect:imageRect];
        
        cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        cell.textLabel.text = @"设置/修改交易密码";
        cell.detailTextLabel.textColor = [UIColor lightGrayColor];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        CYUser *user = [CYLoginHttpTool userData].user;
        [CYHttpTool postWithURL:[CYURL shared].getDealCodeStatus params:@{@"userId":user.userId,@"token":user.token} success:^(id json) {
            CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
            _type = jsonInfo.data;
            if (_type.intValue == 1) {
                cell.detailTextLabel.text = @"已设置";
            }else{
                cell.detailTextLabel.text = @"未设置";
            }
        } failure:^(NSError *error) {
            CYLog(@"error = %@",error);
        }];

    }else if (indexPath.section == 1) {
        UIImage *icon = [UIImage imageWithName:@"2"];
        CGSize itemSize = CGSizeMake(30, 30);
        UIGraphicsBeginImageContextWithOptions(itemSize, NO ,0.0);
        CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
        [icon drawInRect:imageRect];
        
        cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        cell.textLabel.text = @"绑定银行卡";
        cell.detailTextLabel.textColor = [UIColor lightGrayColor];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {

        if (!_bandcheck) {
            CYAlertView(@"您还未绑定银行卡");
        }else{
            CYAlertView(@"已绑定银行卡");
        }
 
        
    }if (indexPath.section == 1) {

       CYBankcardBandTableViewController  *bacd = [CYBankcardBandTableViewController le_loadFromStoryBoard:[CYJumpsTool mainSB]];
        [self.navigationController pushViewController:bacd animated:YES];
        
    }
    if (indexPath.section == 2) {
        CYGetdealCodeVC *gtcode  = [[CYGetdealCodeVC alloc]init];
        [self.navigationController pushViewController:gtcode animated:YES];
    }

}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 200;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 ||indexPath.section == 1 ||indexPath.section == 2||indexPath.section == 3  ) {
        return 50;
    }
    return 104;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return .1f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

#pragma mark -
- (void)carUserAccountRecharge:(CGFloat)account {
    CYUser *user = [CYLoginHttpTool userData].user;
    if (user) {
        [MBProgressHUD showMessage:nil toView:self.view];
        [CYDiscoveryHttpTool carUserAccountRechargeWithParam:@{@"userId": user.userId, @"token": user.token, @"balance": @(account)} success:^(NSString *message) {
            [MBProgressHUD hideHUDForView:self.view animated:NO];
            [MBProgressHUD showSuccess:message];
        } failure:^(NSString *message, BOOL isLogin) {
            [MBProgressHUD hideHUDForView:self.view animated:NO];
            [MBProgressHUD showError:message];
            if (!isLogin) {
                [self.navigationController popViewControllerAnimated:NO];
                [CYLoginHttpTool logoutWithController:self];
            }
        }];
    }
}

- (void)addTabBar:(CYButtonView *)tabBarView {
    CYUser *user = [CYLoginHttpTool userData].user;
    CYWeakObject(wself, self);
    [tabBarView addTabBarButtonWithImageName:@"icon_refund" title:@"充值" description:@"掌上快速充值" showLines:nil showstatus:nil clicked:^{
        if (user) {
            [UIInfomationView showAlertViewWithTitle:@"请输入充值金额" message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] style:UIAlertViewStylePlainTextInput keyboardType:UIKeyboardTypeNumberPad clickAtIndex:^(UIAlertView *alertView, NSInteger buttonIndex) {
                if (buttonIndex == 1) {
                    UITextField *tf = [alertView textFieldAtIndex:0];
                    CYLog(@"tf: %@", tf.text);
                    [wself.view endEditing:YES];
                    CGFloat amount = tf.text.floatValue;
                    if (amount > 0) {
                        [CYGFBTool rechargeAmount:tf.text userType:CYUserTypePerson];
                    } else {
                        [MBProgressHUD showError:@"输入金额错误"];
                    }
                }
            }];
        }
    }];
    
    [tabBarView addTabBarButtonWithImageName:@"7" title:@"提现" description:@"掌上快速提现" showLines:@[@(CYDirectionStatusLeft), @(CYDirectionStatusRight)] showstatus:nil clicked:^{
        UIAlertView *txaler = [[UIAlertView alloc]initWithTitle:@"请输入提现金额" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        [txaler setAlertViewStyle:UIAlertViewStylePlainTextInput];
        [txaler show];
        [txaler showAlertViewWithCompleteBlock:^(NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                _moneycount = [txaler textFieldAtIndex:0];
                CGFloat amount = _moneycount.text.floatValue;
                if (amount > 0) {
                UIAlertView *codealer = [[UIAlertView alloc]initWithTitle:@"请输入交易密码" message:nil delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"确认", nil];
                [codealer setAlertViewStyle:UIAlertViewStylePlainTextInput];
                [codealer show];
                [codealer showAlertViewWithCompleteBlock:^(NSInteger buttonIndex) {
                    if (buttonIndex == 1) {
                         _dealcode.secureTextEntry = YES;
                        _dealcode = [codealer textFieldAtIndex:0];
                        [wself.view endEditing:YES];
                            [CYHttpTool postWithURL:[CYURL shared].withDraw params:@{@"userId":user.userId,@"token":user.token,@"dealCode":_dealcode.text,@"amount":_moneycount.text} success:^(id json) {
                                CYLog(@"json = %@",json);
                                CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
                                if (jsonInfo.isSuccess) {
                                    [MBProgressHUD showSuccess:jsonInfo.message];
                                }else {
                                    [MBProgressHUD showError:jsonInfo.message];
                                }
                            } failure:^(NSError *error) {
                                CYLog(@"error = %@",error);
                                CYAlertView(@"服务器连接失败");
                            }];
                      }
                }];
                }else {
                    [MBProgressHUD showError:@"输入金额错误"];
                }
            }
        }];
            
    }];
    
    [tabBarView addTabBarButtonWithImageName:@"icon_refund" title:@"资金明细" description:@"查看资金明细"     showLines:nil showstatus:nil clicked:^{

        CYAssetDetailVC *assetvc = [[CYAssetDetailVC alloc]init];
        [self.navigationController pushViewController:assetvc animated:YES];
        
     
    }];

    
//    [tabBarView addTabBarButtonWithImageName:@"icon_menu_mysx" title:@"失信联系人" description:@"身边的老赖" showLines:nil clicked:^{
//        
//    }];
}
//-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//   
//    if (buttonIndex == 0 ) {
//        
//    }else if (buttonIndex == 1){
//        //click
//         // 拿到UITextField
//               UIAlertView *codealer = [[UIAlertView alloc]initWithTitle:@"请输入交易密码" message:nil delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"确认", nil];
//        [codealer setAlertViewStyle:UIAlertViewStylePlainTextInput];
//        [codealer show];
//    }
//}

#pragma mark - 重写
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [DSNavigationBar setNavigationBarWithNavigationBar:self.navigationController.navigationBar color:[UIColor clearColor]];
    if (self.isRefresh) {
        [self.tableview.mj_header beginRefreshing];
    } else {
        self.isRefresh = YES;
    }
}

//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated]withDraw.htm;
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
//}

- (void)dealloc {
    CYLog(@"个人充值界面销毁");
    [self.tableview.mj_header endRefreshing];
}
@end
